package cn.com.seederland.gkrpc.client;

import cn.com.seederland.gkrpc.Peer;
import cn.com.seederland.gkrpc.common.utils.ReflectionUtils;
import cn.com.seeederland.gkrpc.transport.TransportClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class RandomTransportSelector implements TransportSelector {

    private static final Logger LOGGER = LoggerFactory.getLogger(RandomTransportSelector.class);

    private List<TransportClient> clients;

    public RandomTransportSelector() {
        clients = new ArrayList<>();
    }

    @Override
    public synchronized void init(List<Peer> peerList, int count, Class<? extends TransportClient> clazz) {
        count = Math.max(count, 1);
        for (Peer peer : peerList) {
            for (int i = 0; i <count; i++) {
                TransportClient client = ReflectionUtils.newInstance(clazz);
                client.createConnection(peer);
                clients.add(client);
            }
            LOGGER.info("连接服务器：{}", peer);
        }
    }

    @Override
    public synchronized TransportClient select() {
        int i = new Random().nextInt(clients.size());
        return clients.remove(i);
    }

    @Override
    public synchronized void release(TransportClient client) {
        clients.add(client);
    }

    @Override
    public synchronized void close() {
        for (TransportClient client:clients) {
            client.closeConnection();
        }
        clients.clear();;
    }
}
